import React, { useEffect, useState, useRef } from "react";
import { Button, Spin } from "antd";
import { useLocation, useNavigate } from "react-router-dom";
import axios from "axios";

const URL = "http://localhost:3001";

const menu = [
    { key: "xueli", label: "学历" },
    { key: "xinzi", label: "薪资" },
    { key: "exp", label: "经验" },
    { key: "years", label: "公司规模" }
];

const defs = {
    xueli: ["不限", "中专/中技", "大专", "本科", "硕士", "博士"],
    xinzi: ["不限", "3K以下", "3-5K", "5-10K", "10-20K", "20-50K", "50K以上"],
    exp: ["不限", "1-3年", "3-5年", "5-10年", "10年以上"],
    years: ["不限", "20-99人", "100-499人", "500-999人", "1000-9999人", "10000人以上"]
};

const defed = {
    xueli: ["不限"],
    xinzi: ["不限"],
    exp: ["不限"],
    years: ["不限"]
};

const st = {
    zhu: {
        display: "flex",
        height: "100vh",
        overflow: "hidden"
    },
    menu: {
        width: "80px",
        backgroundColor: "rgb(246, 246, 246)",
        overflow: "auto"
    },
    menuw: {
        padding: "15px 0",
        textAlign: "center",
        fontSize: "14px",
        color: "rgb(102, 102, 102)"
    },
    menus: {
        color: "rgb(0, 179, 138)",
        backgroundColor: "rgb(255, 255, 255)",
        borderLeft: "2px solid rgb(0, 179, 138)"
    },
    content: {
        flex: 1,
        overflow: "auto",
        padding: "0 15px",
        backgroundColor: "rgb(255, 255, 255)"
    },
    loadingzhu: {
        display: "flex",
        justifyContent: "center",
        alignItems: "center",
        height: "200px"
    },
    section: {
        marginBottom: "20px",
        paddingTop: "15px"
    },
    sections: {
        fontWeight: "bold",
        marginBottom: "10px",
        fontSize: "16px"
    },
    Lists: {
        display: "flex",
        flexWrap: "wrap",
        gap: "10px"
    },
    footer: {
        display: "flex",
        justifyContent: "space-between",
        padding: "15px",
        borderTop: "1px solid rgb(238, 238, 238)",
        position: "sticky",
        bottom: 0,
        backgroundColor: "rgb(255, 255, 255)"
    }
};

export default function Filter() {
    const loc = useLocation();
    const nav = useNavigate();
    const refs = useRef({});

    const [filters, setFilters] = useState(defs);
    const [loading, setLoading] = useState(false);
    const [active, setActive] = useState("xueli");
    const [selected, setSelected] = useState({
        ...defed,
        ...(loc.state?.filter || {})
    });

    // 获取
    const getFilters = async () => {
        const res = await axios.get(`${URL}/filters`);
        return res.data;
    };

    // 获取筛选
    useEffect(() => {
        let Mounts = true;
        const fetchFilters = async () => {
            setLoading(true);
            try {
                const data = await getFilters();
                if (Mounts && data && typeof data === 'object') {
                    setFilters(prev => ({
                        ...defs,
                        ...data
                    }));
                }
            } catch (error) {
                console.error('获取筛选数据失败:', error);
                if (Mounts) {
                    setFilters(defs);
                }
            } finally {
                if (Mounts) {
                    setLoading(false);
                }
            }
        };
        fetchFilters();
        return () => {
            Mounts = false;
        };
    }, []);


    //点击
    const handleOptionClick = (key, value) => {
        if (key === "xinzi" || key === "years") {
            // 单选
            setSelected(sel => ({ ...sel, [key]: [value] }));
        } else {
            // 多选
            setSelected(sel => {
                let arr = sel[key].includes(value)
                    ? sel[key].filter(v => v !== value)
                    : [...sel[key].filter(v => v !== "不限"), value];
                if (arr.length === 0) arr = ["不限"];
                if (value === "不限") arr = ["不限"];
                return { ...sel, [key]: arr };
            });
        }
    };

    // 清除 
    const clear = () => {
        setSelected(defed);
    };

    // 确定
    const irm = () => {
        nav("/", { state: { filter: selected } });
    };

    return (
        <div style={st.zhu}>
            
            <div style={st.menu}>
                {menu.map(item => (
                    <div
                        key={item.key}
                        style={{
                            ...st.menuw,
                            ...(active === item.key ? st.menus : {})
                        }}
                        onClick={() => handleMenuClick(item.key)}
                    >
                        {item.label}
                    </div>
                ))}
            </div>

            
            <div style={st.content}>
                {loading ? (
                    <div style={st.loadingzhu}>
                        <Spin />
                    </div>
                ) : (
                    menu.map(item => (
                        <div
                            key={item.key}
                            ref={el => (refs.current[item.key] = el)}
                            style={st.section}
                        >
                            <div style={st.sections}>
                                {item.label}要求
                            </div>
                            
                        </div>
                    ))
                )}

                
                <div style={st.footer}>
                    <Button onClick={clear}>清除</Button>
                    <Button type="primary" onClick={handleConfirm}>确定</Button>
                </div>
            </div>
        </div>
    );
}